package work.jame.blog.configuration.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import work.jame.blog.framework.exception.user.UserAuthenticationException;
import work.jame.blog.pojo.User;
import work.jame.blog.service.AuthorityService;
import work.jame.blog.service.RoleService;
import work.jame.blog.service.UserService;

import java.util.Objects;

/**
 * 自定义UserDetails服务实现类
 *
 * @author Jame!
 * @date 2023/5/9 下午 9:35
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        User user = userService.getOne(wrapper);
        if (Objects.isNull(user)) {
            throw new UserAuthenticationException("用户名或密码不正确");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setPermissions(authorityService.queryAuthorityCodeByUserId(user.getId()));
        loginUser.addRole(roleService.queryRolesCodeByUserId(user.getId()));
        return loginUser;
    }
}
